package dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import domain.Keyword;
import domain.Resource;
import domain.User;
import domain.util.HibernateFactory;

public class ResourceDAO {

	static SessionFactory fact = HibernateFactory.getSessionFactory();
	static Session session = fact.openSession();
	static Transaction transaction;

	public boolean save(Resource resource) {
		try {
			transaction = session.beginTransaction();

			if (resource.getKeywords() != null)
				for (Keyword k : resource.getKeywords()) {
					session.save(k);
				}

			session.save(resource);
			transaction.commit();
			return true;
		} catch (Exception e) {
			System.out.println("AIDS");
			transaction.rollback();
			return false;
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Resource> getResourcesBy(String key, String value) {
		return session
				.createQuery(
						"FROM domain.Resource WHERE " + key + " = " + "'"
								+ value + "'").list();
	}
	
	@SuppressWarnings("unchecked")
	public static Resource getResourcesById(Long id) {

			Resource resource = null;
			try {
				resource = (Resource) session.get(Resource.class, id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return resource;
	}
	
}
